package com.example.sunflowers.adapters

import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.sunflowers.R
import com.example.sunflowers.data.db.PlantAndGardenPlantings
import com.example.sunflowers.databinding.ListItemGardenPlantingBinding
import com.example.sunflowers.ui.HomeViewPagerFragment
import com.example.sunflowers.ui.HomeViewPagerFragmentDirections
import com.example.sunflowers.viewmodels.PlantAndGardenPlantingsViewModel

/**
 *
 * @Author： LJH
 * @Time： 2024/1/27
 * @description：
 */
class GardenPlantingAdapter
    :ListAdapter<PlantAndGardenPlantings,GardenPlantingAdapter.ViewHolder>(
    GardenPlantingDiffCallback()
){

    class ViewHolder(
        private val binding:ListItemGardenPlantingBinding
    ):RecyclerView.ViewHolder(binding.root){

        init {
            binding.setClickListener { view ->
                binding.viewModel?.plantId?.let {
                    navigateToPlant(it,view)
                }
            }
        }

        private fun navigateToPlant(plantId:String,view:View){
            val direction = HomeViewPagerFragmentDirections
                .actionHomeViewPagerFragmentToPlantDetailFragment(plantId)
            view.findNavController().navigate(direction)
        }

        fun bind(plantings:PlantAndGardenPlantings){
            with(binding){
                viewModel = PlantAndGardenPlantingsViewModel(plantings)
                executePendingBindings()
            }
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            DataBindingUtil.inflate(
                LayoutInflater.from(parent.context),
                R.layout.list_item_garden_planting,
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

}

private class GardenPlantingDiffCallback:ItemCallback<PlantAndGardenPlantings>(){
    override fun areItemsTheSame(
        oldItem: PlantAndGardenPlantings,
        newItem: PlantAndGardenPlantings
    ): Boolean {
        return oldItem.plant.plantId == newItem.plant.plantId
    }

    override fun areContentsTheSame(
        oldItem: PlantAndGardenPlantings,
        newItem: PlantAndGardenPlantings
    ): Boolean {
        return oldItem.plant == newItem.plant
    }
}